//
//  YWPostTroubleTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/17.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWPostTroubleTableViewController.h"
#import "YWSingleSelectEquSystemTypeTableViewController.h"
#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"

#import "Masonry.h"
#import "UIColor+CustomColors.h"
#import "YWCommonTool.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWMission.h"
#import "YWMissionManager.h"
#import "YWResourceManager.h"
#import "YWCirculationManager.h"
#import "YWCirculationInfo.h"
#import "YWLoginUser.h"
#import "YWLoginTool.h"
#import "YWHandler.h"
#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWNotifyManager.h"
#import "YWLocation.h"
#import "YWEquipmentManager.h"

//#import "YWImageView.h"
#import "YWPhotoView.h"
#import "YWEquipment.h"
//#import "YWAlertView.h"
#import "MBProgressHUD.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"
#import "YWTroubleMissionModel.h"
#import "YWEquipmentType.h"

#define KDescriptionTextMax 100

@interface YWPostTroubleTableViewController ()<YWTakePhotoCellDelegate,YWSingleSelectEquSystemTypeTableViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *equipmentDataSource;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) YWEquipmentSystemType * equipmentSystemType;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWPostTroubleTableViewController
- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"报障";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(clickLeftBatItem:)];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.tableFooterView = self.footView;
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
}

- (NSMutableArray *)equipmentDataSource{
    if (!_equipmentDataSource) {
        _equipmentDataSource = [NSMutableArray array];
        [_equipmentDataSource addObjectsFromArray:self.equipmentArray];
        
        YWEquipment *locationPostTrouble = [[YWEquipment alloc] init];
        locationPostTrouble.equipmentId = @"位置报障";
        locationPostTrouble.equipmentName = @"位置报障";
        if (_currentEquipment) {
            locationPostTrouble.qrcodeId = _currentEquipment.qrcodeId;
            locationPostTrouble.locationId = _currentEquipment.locationId;
        }
        if (locationPostTrouble.locationId==0 && self.equipmentArray.count>0){
            YWEquipment *equipment = self.equipmentArray[0];
            locationPostTrouble.qrcodeId = equipment.qrcodeId;
            locationPostTrouble.locationId = equipment.locationId;
        }
        if (locationPostTrouble.locationId==0 && (self.qrCodeId.length>0 || self.locationId>0)){
            locationPostTrouble.qrcodeId = self.qrCodeId;
            locationPostTrouble.locationId = self.locationId;
        }
        if (locationPostTrouble.locationId>0) {
            if (_currentEquipment == nil) {
                _currentEquipment = locationPostTrouble;
            }
            [_equipmentDataSource addObject:locationPostTrouble];
        }
    }
    return _equipmentDataSource;
}

- (void)setEquipmentArray:(NSArray *)equipmentArray{
    _equipmentArray = equipmentArray;
    [self.equipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        equipment.totalImageNameArray = nil;
        equipment.psText = nil;
//        equipment.runTimeParameterArray = nil;
    }];
}

- (YWEquipmentSystemType*)equipmentSystemType{
    if (!_equipmentSystemType) {
        _equipmentSystemType = [[YWEquipmentManager shareManager] equipmentSystemTypeWithEquipmentTypeId:_currentEquipment.equipmentTypeId];
        //当选择位置报障的时候，默认系统第一个
        if (_equipmentSystemType==nil) {
            _equipmentSystemType = [[[YWEquipmentManager shareManager] allEquipmentSystemType] firstObject];
        }
    }
    return _equipmentSystemType;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.equipmentDataSource.count;
    }else{
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0 || indexPath.section == 1) {
        return 44;
    }else if (indexPath.section == 2){
        return 90;
    }else{
        CGFloat imageH = YWPhotoSize*(_currentEquipment.totalImageNameArray.count/4+1) + YWPhotoGap*(_currentEquipment.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *identifier = @"YWPostTroubleTableViewControllerIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        YWEquipment *equipment = self.equipmentDataSource[indexPath.row];
        cell.textLabel.text = equipment.equipmentName?:@"";
        if ([equipment.equipmentId isEqualToString:_currentEquipment.equipmentId]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }else{
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        return cell;

    }else if (indexPath.section == 1){
        static NSString *identifier = @"YWPostTroubleTableViewControllerIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        cell.textLabel.text = self.equipmentSystemType.systemTypeName;
        return cell;
    }else if (indexPath.section == 2){
        YWWriteNoteCell * cell  = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.textViewPlaceHolder = @"请描述故障信息以及设备的具体位置等信息";
        cell.equipment = _currentEquipment;
        return cell;
    }else{
        YWTakePhotoCell * cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.totalImageNameArray = _currentEquipment.totalImageNameArray;
        cell.delegate = self;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWEquipment *equipment = self.equipmentDataSource[indexPath.row];
        _currentEquipment = equipment;
        _equipmentSystemType = nil;
        [self.tableView  reloadData];
    }else if (indexPath.section == 1){
        if ([_currentEquipment.equipmentId isEqualToString:@"位置报障"]) {YWSingleSelectEquSystemTypeTableViewController * selectSystemTypeVC = [[YWSingleSelectEquSystemTypeTableViewController alloc] init];
            selectSystemTypeVC.currentEquipmentSystemType = self.equipmentSystemType;
            selectSystemTypeVC.delegate = self;
            [self.navigationController pushViewController:selectSystemTypeVC animated:YES];
        }else{
            UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"提示" message:@"如果您要切换报障类别\n请选择位置报障" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alertController animated:YES completion:nil];
            [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];}
    }
}

#pragma mark - Table view head view

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWPostTroubleTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.frame = CGRectMake(15, 0, (SCREEN_WIDTH-15*3)/2, 35);
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    
    return headerView;
    
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        return @"选择设备或位置";
    }else if (section==1){
        return @"报障类别";
    }else if (section==2){
        return @"故障描述";
    }else{
        return @"拍照上传";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    _currentEquipment.totalImageNameArray = arr;
    
    [self.tableView reloadData];
}

#pragma mark - button event action 

- (void)handlePostButtonEvent
{
    if (_currentEquipment.psText.length==0) {
        [YWCommonTool showTextHUDWithContent:@"请填写故障描述"];
        return;
    }
    if ([YWCommonTool isContainsEmoji:_currentEquipment.psText]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (_currentEquipment.psText.length > KDescriptionTextMax) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextTroubleDescriptionMax, nil)];
        return;
    }
    
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:NSLocalizedString(kTextConfirmSubmitPostTrouble, nil) preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.HUD.labelText = NSLocalizedString(kTextSubmitPostTrouble, nil);
        [self.HUD show:YES];

        YWReportTroubleModel * reportTrouble = [self createPostReportTrouble];
        BOOL saveReportTrouble = [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:@[reportTrouble]];
        
        NSArray* pictures = [self createPictures:reportTrouble];
        BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
        if (saveReportTrouble && savePicturesToDB) {
            [self.HUD hide:YES];
            //创建保存流转信息
            [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypePostTrouble troubleId:reportTrouble.troubleId recipient:nil note:nil];
            if ([self.delegate respondsToSelector:@selector(passBackReportTrouble:)]) {
                [self.delegate passBackReportTrouble:reportTrouble];
            }else{
                //上传
                [[YWReportTroubleManager shareManager] startUploadReportTrouble:reportTrouble pictures:pictures];
            }
            
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextConfirmSubmitPostTroubleFinished, nil)];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[YWNotifyManager shareManager] postTroubleNotifyWithStatu:_currentEquipment.equipmentId];
                [self popToSomeViewController];
            });
        }
        else {
            [self.HUD hide:YES];
            YWLog(@"保存数据库失败");
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitPostTroubleFail, nil)];
        }
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}


- (YWReportTroubleModel*)createPostReportTrouble{
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970] * 1000;
    YWReportTroubleModel * reportTrouble = [[YWReportTroubleModel alloc] init];
    reportTrouble.troubleId = -1 * [YWCommonTool randNumber];
    reportTrouble.maintenanceTypeId = YWMaintenanceTypeTrouble;
    reportTrouble.troubleStatus = YWTroubleMissionStatusUnAssign;
    reportTrouble.note = [_currentEquipment.psText stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    reportTrouble.reportTime = nowTime;
    reportTrouble.equipment = _currentEquipment;
    YWLoginUser* loginUser = [YWLoginTool loginUser];
    YWHandler *creator = [[YWHandler alloc]init];
    creator.uniqueId = loginUser.uniqueId;
    creator.userName = loginUser.userName;
    creator.mobile = loginUser.mobile;
    creator.headIcon = loginUser.headIcon;
    reportTrouble.reporter = creator;
    reportTrouble.channel = YWPostTroubleTypeEwinApp;
    reportTrouble.reportTime = nowTime;
    if (![self.equipmentSystemType.systemTypeName isEqualToString:@"无"]) {
        reportTrouble.systemTypeId = self.equipmentSystemType.systemTypeId;
    }
    if (_currentEquipment.qrcodeId.length) {
        reportTrouble.qrcodeId = _currentEquipment.qrcodeId;
    }else if (self.qrCodeId){
        reportTrouble.qrcodeId = self.qrCodeId;
    }
    if (_currentEquipment.locationId>0) {
        YWLocation * location = [[YWBuildingManager shareManager] locationWithId:_currentEquipment.locationId];
        reportTrouble.location = location;
    }else if (self.locationId){
        YWLocation * location = [[YWBuildingManager shareManager] locationWithId:self.locationId];
        reportTrouble.location = location;
    }
    YWBuilding* building = reportTrouble.building;
    if (building == nil) {
        building = [[YWBuildingManager shareManager] buildingWithEquipmentId:reportTrouble.equipment.equipmentId];
    }
    if (building==nil) {
        building = [[YWBuildingManager shareManager] buildingWithLocationId:reportTrouble.location.locationId];
    }
    reportTrouble.building = building;
    reportTrouble.uniqueTag = [YWCommonTool randStringId];
    return reportTrouble;
}

- (NSArray*)createPictures:(YWReportTroubleModel*)mission
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [_currentEquipment.totalImageNameArray count]; i++) {
        YWPicture* picture = [[YWPicture alloc] init];
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = _currentEquipment.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureUploadStatusNull;
        picture.missionId = mission.troubleId;
        picture.maintenanceType = mission.maintenanceTypeId;
        picture.equipmentId = mission.equipment.equipmentId;
        [pictures addObject:picture];
    }
    return pictures;
}

- (void)clickLeftBatItem:(id)sender{
    if (_currentEquipment.psText.length>0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出此次编辑?" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self popToSomeViewController];
        }]];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        [self popToSomeViewController];
    }
}

-(void)popToSomeViewController{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}
#pragma mark-YWSingleSelectEquSystemTypeTableViewControllerDelegate
- (void)popSelectedEquipmentSystemType:(YWEquipmentSystemType*)equipmentSystemType{
    self.equipmentSystemType = equipmentSystemType;
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [self.equipmentArray enumerateObjectsUsingBlock:^(YWEquipment*  _Nonnull equipment, NSUInteger idx, BOOL * _Nonnull stop) {
        equipment.totalImageNameArray = nil;
        equipment.psText = nil;
//        equipment.runTimeParameterArray = nil;
    }];
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 20*2+kButtonH);
        footView.backgroundColor = [UIColor customBackgroudColor];
        
        UIButton* troubleButton = [UIButton buttonWithType:UIButtonTypeSystem];
        troubleButton.frame = CGRectMake(10, 20, SCREEN_WIDTH-20, kButtonH);
        [troubleButton setBackgroundColor:[UIColor whiteColor]];
        [troubleButton setTitle:@"提交" forState:UIControlStateNormal];
        if ([self.delegate respondsToSelector:@selector(passBackReportTrouble:)]) {
            [troubleButton setTitle:@"确定" forState:UIControlStateNormal];
        }
        troubleButton.titleLabel.font = kBoldTitleFont;
        [troubleButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        troubleButton.layer.borderColor = [UIColor customBlueColor].CGColor;
        troubleButton.layer.borderWidth = 1.0;
        troubleButton.clipsToBounds = YES;
        troubleButton.layer.cornerRadius = 5.0;
        
        [troubleButton addTarget:self action:@selector(handlePostButtonEvent) forControlEvents:UIControlEventTouchUpInside];
        [footView addSubview:troubleButton];
        _footView = footView;
    }
    return _footView;
}

@end
